#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;


#define NUM 1024

void Write(int wfd)
{
    string s = "I am child";
    int pid = getpid();
    int num = 0;

    char buffer[NUM];

    while(true)
    {
        // 构建发送的字符串
        // snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), pid, num++);

        // // 写入数据给父进程  system call
        // write(wfd, buffer, strlen(buffer));

        char ch = 'c';
        write(wfd, &ch, 1);
        cout << num++ << endl;

        if(num == 5)
            break;
    }
}

void Read(int rfd)
{
    char buffer[NUM];

    sleep(10);

    while(true)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer));

        if(n > 0)
        {
            buffer[n] = '\0'; // 防止越界读取
            cout << "father get a message[" << getpid() << "]# " << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "read failure!" << endl;
            break;
        }
        else
            break;
    }
}

int main()
{
    int pipefd[2]={0};
    int n = pipe(pipefd);
    if(n < 0)
        return 1;

    pid_t id = fork();
    if(id < 0)
        return 2;
    else if(id == 0)
    {
        // child
        close(pipefd[0]);

        Write(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    else
    {
        // father
        close(pipefd[1]);

        Read(pipefd[0]);

        pid_t rid = waitpid(id, nullptr, 0);
        if(rid < 0)
            return 3;

        close(pipefd[0]);
    }
    return 0;
}